package org.example.thymeleaf.demo.demos.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.example.thymeleaf.demo.demos.entity.WordTemplate;
import org.example.thymeleaf.demo.demos.service.MergeTemplateService;
import org.example.thymeleaf.demo.demos.service.WordTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.rowset.serial.SerialBlob;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * (WordTemplate)表控制层
 *
 * @author makejava
 * @since 2024-09-11 09:23:37
 */
@RestController
@RequestMapping("/wordTemplate")
public class WordTemplateController{
    /**
     * 服务对象
     */
    @Resource
    private WordTemplateService wordTemplateService;

    @Resource
    private MergeTemplateService mergeTemplateService;


    @PostMapping("/save")
    public boolean save(@RequestParam String name , MultipartFile value) throws IOException, SQLException {
        byte[] bytes = value.getBytes();
        return wordTemplateService.save(WordTemplate.builder().name(name).value(bytes).build());
    }

    @GetMapping("/show/{id}")
    public String showDoc(@PathVariable("id") Integer id){
        byte[] value = wordTemplateService.getById(id).getValue();
        return Base64.getEncoder().encodeToString(value);
    }

    @PostMapping("/marge")
    public String margeWord(@RequestParam("ids") List<String> ids) throws IOException {
        List<byte[]> byteList = new ArrayList<>();
        ids.forEach(id ->{
            WordTemplate wordTemplate = wordTemplateService.getOneOpt(new LambdaQueryWrapper<WordTemplate>().eq(WordTemplate::getId, Integer.parseInt(id))).orElseThrow(() -> new RuntimeException("不存在的id" + id));
            byteList.add(wordTemplate.getValue());
        });
        byte[] bytes = wordTemplateService.mergeWord(byteList);
        mergeTemplateService.saveByBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes);
//        return wordTemplateService.mergeWordTest(byteList);
    }


}

